package gc;

import java.util.concurrent.TimeUnit;

public class FinalizeEscapeGC {
    private static FinalizeEscapeGC obj;

    void isAlive() {
        System.out.println("i am alive : " + Thread.currentThread());
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println("finalize invoked : " + Thread.currentThread());
        obj = this; // save this
    }

    static void test() {
        obj = null;
        System.gc();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(obj == null)
            System.out.println("obj is dead : " + Thread.currentThread());
        else
            obj.isAlive();
    }

    public static void main(String[] args) {
        obj = new FinalizeEscapeGC();
        System.out.println("------ first -------");
        test();
        System.out.println("------ second -------");
        test();
    }
}
